package es.pawer.android.listacompras.data;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.database.Cursor;

public class ShoppingListDao extends AbstractLiteDAO<ShoppingListTO> {
	
	private enum ColumnNames {
			ID,
			NAME,
			CREATED
	};
	
	private static final String TABLENAME="LIST";
	
	private static final SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");

	@Override
	protected ShoppingListTO obtainElement(Cursor c, int pos) {
		ShoppingListTO g=null;
		if (c!=null && c.moveToPosition(pos)) {
			g= new ShoppingListTO();
			int index=c.getColumnIndex(ColumnNames.ID.name());
			g.setId(c.getInt(index));
			index=c.getColumnIndex(ColumnNames.NAME.name());
			g.setName(c.getString(index));
			index=c.getColumnIndex(ColumnNames.CREATED.name());

			//It's a date, but there is no 'getDate' in the Cursor API
			try {
				g.setCreated(sdf.parse(c.getString(index)));
			} catch (ParseException e) {
				g.setCreated(new Date());
			}
			
		}
		return g;
	}

	@Override
	public int delete(ShoppingListTO sl) throws DataException {
		if (sl==null || sl.getId()<0) {
			throw new DataException("ShoppingTO is empty or null");
		}
		int rows=MyDatabaseHelper.getWritableDB().delete(
				getTableName(), "NAME=?", new String[] {String.valueOf(sl.getId())});
		return rows;
	}

	@Override
	public ShoppingListTO getById(ShoppingListTO sl) {
		Cursor c=MyDatabaseHelper.getWritableDB().query(getTableName(), null,
				ColumnNames.ID.name()+"=?", new String[] {String.valueOf(sl.getId())}, null, null, null);
		sl=this.obtainElement(c, 0);
		return sl;
	}

	@Override
	public String getTableName() {
		return TABLENAME;
	}


	@Override
	public int update(ShoppingListTO sl) throws DataException {
		ContentValues values = getValues(sl);
		int r=MyDatabaseHelper.getWritableDB().update(getTableName(), values, "name=?",
				new String[] { String.valueOf(sl.getId()) });
		return r;
	}

	@Override
	protected ContentValues getValues(ShoppingListTO sl) throws DataException {
		if (sl==null || sl.getId()<0) {
			throw new DataException("ShoppingTO is empty or null");
		}
		ContentValues cv = new ContentValues();
		cv.put(ColumnNames.ID.name(), sl.getId());
		cv.put(ColumnNames.NAME.name(), sl.getName());
		cv.put(ColumnNames.CREATED.name(), sdf.format(sl.getCreated()));
		return cv;
	}

	@Override
	public long insert(ShoppingListTO s) throws DataException {
		long id=super.insert(s);
		s.setId(id);
		return id;
	}
}
